package com.yixing.tech.wcs.controller;

import com.yixing.tech.common.base.BaseControl;
import com.yixing.tech.common.base.BaseResponse;
import com.yixing.tech.common.base.Rs;
import com.yixing.tech.common.base.BusinessException;
import com.yixing.tech.common.tcp.manage.EndpointManager;
import com.yixing.tech.common.tcp.manage.TcpClientEndpoint;
import com.yixing.tech.wcs.domain.vo.EndpointVO;
import com.yixing.tech.wcs.tcp.InteractionConsumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping(value = "/tbea/ic/wcs/endpoint")
@Slf4j
public class EndpointController extends BaseControl {

    @Resource
    EndpointManager endpointManager;

    @Resource
    InteractionConsumer interactionConsumer;

    @PostMapping("/create")
    public Rs<Object> createEndpoint(@RequestBody EndpointVO endpointVO) throws BusinessException {
        EndpointVO res = new EndpointVO();
        try {
            TcpClientEndpoint endpoint = endpointManager.createTcpClientEndpoint(endpointVO.getRemoteHost(),
                    endpointVO.getRemotePort(), endpointVO.getIsOpen(), interactionConsumer.consumeFunc());
            res.setEid(endpoint.getEid());
            res.setConnected(endpointVO.getConnected());
            res.setIsOpen(endpointVO.getIsOpen());
        }catch (Exception ex) {
            throw new BusinessException(ex.getMessage());
        }
        return Rs.ok(res);
    }

    @GetMapping("/list")
    public Rs<Object> listEndpoints() {
        List<Map<String, Object>> maps = endpointManager.listEndpoints();
        return Rs.ok(maps);
    }

    @PostMapping("/send")
    public Rs<Object> sendMessage(@RequestBody EndpointVO endpointVO) {
        // 发送消息
        endpointManager.sendMsgByTcpClientEndpoint(endpointVO.getEid(), endpointVO.getMessage());
        return Rs.ok();
    }

    @PostMapping("/close/{eid}")
    public Rs<Object> closeEndpoint(@PathVariable String eid) {
        // 关闭端点
        endpointManager.closeTcpClientEndpoint(eid);
        return Rs.ok();
    }

    @GetMapping("/listPodInteraction")
    public Rs<Object> listPodInteraction() {
        // 查询成功
        return Rs.ok(interactionConsumer.listPodInteractionState());

    }

    @PostMapping("/addPodInteraction")
    public Rs<Object> addPodInteraction(@RequestBody Map<String, String> param) throws BusinessException {
        // 插入成功
        interactionConsumer.addPodInteractionState(param.get("podCode"), param.get("stateName"));
        return Rs.ok();
    }

    @PostMapping("/removePodInteraction/{podCode}")
    public Rs<Object> removePodInteraction(@PathVariable String podCode) {
        // 删除成功
        interactionConsumer.removePodInteractionState(podCode);
        return Rs.ok();
    }
}
